<template>
  <!-- Banner & Image 通用组件 -->
  <div class="image-content">
    <p class="desc">添加图片 (最多{{ len }}张，可拖动排序）</p>

    <vuedraggable :list="list.data" v-if="list.data && list.data.length > 0" class="image-list">
      <template #item="{ element, index }">
        <li class="item">
          <div class="l-info">
            <p
              ><span class="sort">排序{{ index + 1 }}</span></p
            >
            <!-- <p>
              <span>名称：</span>
              <span class="text">{{ element && element.name }}</span>
            </p> -->
            <div @click="urlPopup(index, element)">
              <p>
                <span>链接业务类型：</span>
                <span class="text" v-if="element.type">
                  {{ element.type }}
                  <DictLabel
                    v-if="element.type"
                    :dictType="'shop_bus_type'"
                    :dictValue="element.type"
                  />
                </span>
                <span v-else class="link">请选择链接业务类型</span>
              </p>
              <p v-if="element.type == 0">
                <span>链接地址：</span>
                <span class="text">{{ element.link }}</span>
              </p>
              <p v-if="element.type == 1">
                <span>促销类型：</span>
                <span class="text">{{ element.busName }}</span>
              </p>
              <p v-if="element.type == 2">
                <span>产品：</span>
                <span class="text">{{ element.busName }}</span>
              </p>
              <p v-if="element.type == 3">
                <span>产品系列：</span>
                <span class="text">{{ element.busName }}</span>
              </p>
              <p v-if="element.type == 5">
                <span>通告类型：</span>
                <span class="text">{{ element.busName }}</span>
              </p>

              <p>
                <span>描述：</span>
                <span class="text">{{ element.remarks }}</span>
              </p>
            </div>
          </div>
          <div class="r-image">
            <div @click="removeImage(index)" class="el-icon-close">
              <Icon icon="simple-line-icons:close" />
            </div>
            <!-- <span @click="removeImage(index)" class="el-icon-close"></span> -->
            <div class="image-box" @click="addImage(index)">
              <img :src="element && element.url" />

              <!-- <span @click="addImage(index)" class="el-icon-edit-outline"></span> -->
            </div>
          </div>
        </li>
      </template>
    </vuedraggable>
    <div v-if="list.data && list.data.length < len">
      <el-button type="primary" icon="el-icon-plus" @click="addImage(null)" class="add-image">
        添加图片
      </el-button>
      <p class="size">（建议尺寸：{{ size }}）</p>
    </div>
    <el-upload :http-request="upload" :show-file-list="false" multiple action style="display: none">
      <el-button ref="elupload" type="primary"> 添加图片 </el-button>
    </el-upload>
    <BasicModal
      @register="registerModal"
      :title="'请完善图片信息'"
      width="40%"
      :showFooter="true"
      @ok="confirm"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  // import { BasicUpload } from '/@/components/Upload';
  import { Icon } from '/@/components/Icon';
  import { reactive, ref, computed, onMounted, unref } from 'vue';
  import vuedraggable from 'vuedraggable';
  import { ElMessage } from 'element-plus';
  import { saveFile, getBase64WithFile } from '/@/api/shop/shop';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { DictLabel } from '/@/components/Dict';

  // import { basInvTreeData } from '/@/api/bas/inv/basInv';
  import { shopProductClsTreeData } from '/@/api/shop/product/shopProductCls';

  const [registerModal, { openModal, closeModal }] = useModal();

  const inputFormSchemas: FormSchema[] = [
    {
      label: '链接业务类型',
      field: 'type',
      component: 'Select',
      componentProps: ({ schema, formModel }) => {
        return {
          dictType: 'shop_bus_type',
          allowClear: true,
          onChange: (e: ChangeEvent) => {
            console.log(e);
            formModel.busKey = '';
            formModel.busName = '';
            console.log(formModel, schema, '===========');
          },
        };
      },
    },
    {
      label: '链接地址',
      field: 'link',
      component: 'Input',
      ifShow: (e) => {
        return e.model.type == 0 ? true : false;
      },
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: '促销类型',
      field: 'busKey',
      fieldLabel: 'busName',
      component: 'ListSelect',
      ifShow: (e) => {
        return e.model.type == 1 ? true : false;
      },
      componentProps: {
        selectType: 'basProductSellSelect',
      },
    },
    {
      label: '产品类',
      // basInvSelect
      field: 'busKey',
      fieldLabel: 'busName',
      component: 'ListSelect',
      ifShow: (e) => {
        return e.model.type == 2 ? true : false;
      },
      componentProps: {
        selectType: 'basInvSelect',
      },
    },
    {
      label: '产品系列',
      field: 'busKey',
      fieldLabel: 'busName',
      component: 'ListSelect',
      ifShow: (e) => {
        return e.model.type == 3 ? true : false;
      },
      componentProps: {
        // api: shopProductClsTreeData,
        // allowClear: true,
        selectType: 'basProductClsSelect',
      },
    },
    {
      label: '通告类型',
      field: 'busKey',
      fieldLabel: 'busName',
      component: 'ListSelect',
      ifShow: (e) => {
        return e.model.type == 5 ? true : false;
      },
      componentProps: {
        selectType: 'noticeSelect',
      },
    },

    {
      label: '图片描述',
      field: 'remarks',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
  ];
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  // let dataMap: any = ref(null);
  // let bizKey: any = ref(null);
  // let loadTime: any = ref(new Date().getTime());

  const props = defineProps({
    data: { type: Object, default: {} },
  });
  let list: any = ref({});
  let url: any = ref('');
  let form: any = ref({});
  let index: any = ref(null);
  let show: any = ref(false);
  let imageIndex: any = ref(null);
  let elupload: any = ref(null);

  const size = computed(() => {
    return list.value.type == 'homeBanner' ? '1920*980' : '750*750';
  });
  const len = computed(() => {
    return list.value.type == 'homeBanner' ? 5 : 8;
  });
  onMounted(() => {
    console.log(props.data, 'props.data=========');
    list.value = props.data;
  });

  // function close() {
  //   show.value = false;
  //   url.value = '';
  // }
  function confirm() {
    // list.value['data'][index.value]['link'] = url.value;
    let data = getFieldsValue();
    list.value['data'][index.value] = { ...list.value['data'][index.value], ...data };
    console.log(list.value['data'][index.value], '=========');

    closeModal();
    // close();
  }
  async function urlPopup(index1, item) {
    await openModal(true);
    // show.value = true;
    index.value = index1;
    // url.value = link;
    form.value = { ...item };
    setFieldsValue(form.value);
  }
  function removeImage(index) {
    list.value.data.splice(index, 1);
  }
  function addImage(index) {
    console.log(1111111111111111);
    // console.log(dataMap.value,'dataMap==========');
    imageIndex.value = index;
    elupload.value?.$.vnode.el?.click();
  }

  async function upload(params) {
    console.log(params, 'params======');

    const len = list.value.data.length;

    if (len >= len.value) {
      ElMessage.error(`最多添加${len.value}张图片!`);
      return;
    }
    const file = params.file,
      fileType = file.type;

    const verifyList = [
      {
        text: '只能上传图片格式png、jpg、gif!',
        result: fileType.indexOf('image') != -1,
      },
      {
        text: '只能上传大小小于5M',
        result: file.size / 1024 / 1024 < 5,
      },
    ];

    for (let item of verifyList) {
      if (!item.result) {
        ElMessage.error(item.text);
        return;
      }
    }

    await getBase64WithFile(file).then(async ({ result: fileUrl }) => {
      const res = await saveFile({
        base64: fileUrl,
        // id: list.value.id,
        fileName: file.name,
        uploadType: 'image',
      });

      file.fileUpload = res.fileUpload;
      console.log(res);
      console.log(file.fileUpload, 'file.fileUpload+++++');
    });

    const form = new FormData();
    form.append('file', file);
    form.append('clientType', 'multipart/form-data');

    const index = imageIndex.value;
    const data = {
      name: file.name,
      url: URL.createObjectURL(file),
      form,
      fileUpload: file.fileUpload ? file.fileUpload : '',
    };

    if (index !== null) {
      list.value.data[index] = data;
      // this.$set(list.data, index, data)
    } else {
      list.value.data.push(data);
    }
  }
</script>

<style lang="less" scoped>
  .image-content {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    height: 100%;
    overflow: hidden;
    .desc {
      text-align: center;
      font-size: 12px;
      color: #666;
      margin: 18px 0;
      padding-bottom: 10px;
      border-bottom: 1px dashed #ddd;
    }
    .size {
      text-align: center;
      font-size: 12px;
      color: #999;
      margin-bottom: 0;
    }
    .add-image {
      width: calc(100% - 20px);
      height: 34px;
      line-height: 34px;
      padding: 0;
      font-size: 12px;
      margin-left: 10px;
      margin-top: 10px;
    }
    .image-list {
      margin: 0;
      padding: 0 10px;
      overflow: auto;
      &::-webkit-scrollbar-thumb {
        background: #dbdbdb;
        border-radius: 10px;
      }
      &::-webkit-scrollbar-track {
        background: #f6f6f6;
        border-radius: 10px;
      }
      &::-webkit-scrollbar {
        width: 6px;
      }
      li {
        list-style: none;
        background: #f7f8f9;
        border-radius: 4px;
        padding: 6px 14px 10px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        &.disable div {
          pointer-events: none;
          user-select: none;
        }
        .l-info {
          font-size: 12px;
          padding-top: 8px;
          width: calc(100% - 70px);
          p {
            margin: 12px 0 0;
            white-space: nowrap;
            overflow: hidden;
            display: flex;
            .link {
              color: #1b8bff;
              cursor: pointer;
            }
            .text {
              white-space: nowrap;
              text-align: -webkit-auto;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
        .r-image {
          text-align: right;
          .el-icon-close {
            color: #999;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 6px;
            cursor: pointer;
            &:hover {
              color: red;
            }
          }
          .image-box {
            width: 70px;
            height: 70px;
            border-radius: 5px;
            overflow: hidden;
            position: relative;
            background: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            &::before {
              content: '';
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              background: rgba(0, 0, 0, 0.5);
              opacity: 0;
              transition: all 0.3s;
            }
            span {
              position: absolute;
              top: 50%;
              left: 50%;
              color: #fff;
              transform: translate(-50%, -50%);
              font-size: 20px;
              cursor: pointer;
              opacity: 0;
              transition: all 0.3s;
            }
            img {
              max-width: 100%;
            }
            &:hover {
              &::before,
              span {
                opacity: 1;
              }
            }
          }
        }
      }
    }
  }
</style>
